package com.umeox.watch.moto.dataservice.utils

import com.umeox.watch.moto.dataservice.db.model.LocationPeriod
import java.util.*
import kotlin.time.ExperimentalTime
import kotlin.time.days
import kotlin.time.hours
import kotlin.time.minutes
import kotlin.time.seconds


object CareTimeUtil {
    private val now get() = Calendar.getInstance()

    @JvmStatic
    fun findNextBean(data: List<LocationPeriod>): LocationPeriod? {
        val result = mutableListOf<Pair<LocationPeriod, Long>>()
        data.forEach {
            result.add(getNextTimeOfBean(it))
        }
        if (result.isNotEmpty()) {
            val sorted = result.sortedBy { it.second }
            return sorted[0].first
        }
        return null
    }

    @OptIn(ExperimentalTime::class)
    private fun getNextTimeOfBean(bean: LocationPeriod): Pair<LocationPeriod, Long> {
        val daysBin = Integer.parseInt(bean.repeatExpression, 2)
        if (daysBin == 0 || daysBin > 127) {
            throw IllegalArgumentException("重复天数无效 repeatExpression=${bean.repeatExpression}")
        }
        val now = now
        val nowBin = 64 shr (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1)

        val nowTime = now.time.hours.hours + now.time.minutes.minutes

        val startSplit = bean.startTime.split(":")
        val startHour = startSplit[0].toInt()
        val startMinute = startSplit[1].toInt()
        val startTime = startHour.hours + startMinute.minutes

        val endSplit = bean.endTime.split(":")
        val endHour = endSplit[0].toInt()
        val endMinute = endSplit[1].toInt()
        val endTime = endHour.hours + endMinute.minutes
        if (nowBin and daysBin != 0) {
            //匹配到当天
            if (nowTime < endTime) {
                if (nowTime < startTime) {
                    val time = (startTime - nowTime).inWholeMilliseconds + System.currentTimeMillis()
                    return Pair(bean, time)
                } else {
                    val nextTime = nowTime + bean.freq.seconds
                    if (nextTime < endTime) {
                        //下次时间未达到结束时间
                        val time = bean.freq * 1000L + System.currentTimeMillis()
                        return Pair(bean, time)
                    }
                }
            }
        }

        //当天没有，往后找
        var nextDays = 0
        var nextDayBin = nowBin
        do {
            nextDayBin = if (nextDayBin == 1) {
                64
            } else {
                nextDayBin shr 1
            }
            nextDays++
        } while (daysBin and nextDayBin == 0)

        val leftTimeOfToday = (1.days - nowTime).inWholeMilliseconds
        val result = leftTimeOfToday + //当天剩余时间
                (nextDays - 1).days.inWholeMilliseconds + //天数
                startTime.inWholeMilliseconds + //开始时间
                System.currentTimeMillis()

        val time = (result / 60000) * 60000
        return Pair(bean, time) //抹掉秒数
    }
}
